package com.sf.tools.generate;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.sf.tools.common.ConnectionFactory;
import com.sf.tools.common.PropertyUtil;
import com.sf.tools.common.Version;
import com.sf.tools.common.VersionDao;

public class SysUpdate {

	private static VersionDao dao = new VersionDao();
	
	public static Version getNewVersion(){
		Version version = dao.load();
		String dbVersion = version.getVersion();
		String currVersion = PropertyUtil.getKey("version");
		if(!currVersion.equals(dbVersion)){
			return version;
		}
		return null;
	}
	
	public static ByteArrayInputStream InputStream(int type) {
		InputStream is = null;
		Connection conn = ConnectionFactory.getIntance().getConnection();
		PreparedStatement pstm = null;
		ResultSet rs = null;
		String sql = "";
		if(0 == type){
			sql = "select id,version,blob from tb_version where version=(select max(version) from tb_version)";
		}else if(1 == type){
			sql = "select id,version,blob from tb_version where version is null";
		}
		Version version = null;
		try {
			pstm = conn.prepareStatement(sql);
			rs = pstm.executeQuery();
			if(rs.next()){
				String id = rs.getString(1);
				String v = rs.getString(2);
				Blob blob = rs.getBlob(3);
				version = new Version(id,v,blob);
			}
			
			if (version != null && version.getBlob() != null) {
				is = version.getBlob().getBinaryStream();
				byte[] buffer = new byte[(int)version.getBlob().length()];
				int readCount = is.read(buffer);
				if (readCount < 1) {
					return null;
				}
				return new ByteArrayInputStream(buffer);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ConnectionFactory.getIntance().close(rs, pstm, conn);
			if (is != null) {
				try {
					is.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
		return null;
	}
}
